package net.example.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;

import net.example.activity.Group_Friend_SelectorActivity;
import net.example.activity.ChatActivity;
import net.example.activity.adapter.GroupAdapter;
import net.example.model.Group_Friend_SelectorType;
import net.example.model.event.ChatEvent;
import net.example.manager.GGApplication;
import net.example.manager.ClientGlobalCache;
import net.example.db.LastChatRecordPersister;
import net.example.manager.Manager;
import net.example.model.GGGroup;
import net.example.model.event.ClickToChatEvent;
import net.example.model.event.GroupDeletedNotifyEvent;
import net.example.model.event.GroupInfoChangedEvent;
import net.example.model.event.GroupUserChangedEvent;
import net.example.ggtalk.R;
import net.example.utils.ConfigUtils;
import net.example.utils.IntentUtils;
import net.example.utils.LogHelper;
import net.example.activity.view.sessionview.MessageItem;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 */
public class GroupFragment extends Fragment  implements AdapterView.OnItemClickListener {
	private View view;
	private ListView mListView;
	private List<MessageItem> mMessageItems = new ArrayList<MessageItem>();
	private GroupAdapter adapter;
	private Handler mHandler = new Handler();
	private boolean isLongState = false;
	private HashMap<Integer, Boolean> checkedItemMap = new HashMap<Integer, Boolean>();
	MessageItem currentItem = null;


	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		view = inflater.inflate(R.layout.fragment_group, container, false);
		initViews();
		ImageButton btn_moveToAddGroup=(ImageButton) view.findViewById(R.id.plus_btn);
		btn_moveToAddGroup.setVisibility(View.VISIBLE);
		btn_moveToAddGroup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(getActivity(), Group_Friend_SelectorActivity.class);
				intent.putExtra("groupFriendSelectorType", Group_Friend_SelectorType.AddMember4CreateGroup);
				getActivity().startActivity(intent);
			}
		});
		return view;
	}

	private void initViews() {
		if (!EventBus.getDefault().isRegistered(this)) {
			EventBus.getDefault().register(this);
		}
		geneItems();
		mListView = (ListView) view.findViewById(R.id.xListView);
		mListView.setOnItemClickListener(this);
		adapter = new GroupAdapter(getActivity(), mMessageItems);
		mListView.setAdapter(adapter);
	}



	/**
	 * @Function:填充数据
	 */
	private void geneItems() {
		Collection<GGGroup> groups = ClientGlobalCache.getInstance().getGroups();
		mMessageItems.clear();
		List<MessageItem> list = LastChatRecordPersister.getInstance().getMyLastMessageRecord();
		for (GGGroup group : groups) {
			MessageItem item = new MessageItem();
			item.title = group.getName();
			item.senderID = group.getGroupID();
			item.lastWord = group.getAnnounce();
			item.isGroup=true;
			for (MessageItem messageItem : list) {
				if (messageItem.isGroup && messageItem.senderID.equals(item.senderID)) {
					item.time = messageItem.time;
					item.isNewMsg = messageItem.isNewMsg;
					break;
				}
			}
			mMessageItems.add(item);
		}
	}

	/**
	 * @Function:点击监听
	 */
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (isLongState) {
			LogHelper.i("编辑状态下点击事件");
			putCheckedItemMap((int) arg3);
			updateListViewByDataSourceNoChange(true);
		} else {
			MessageItem item = (MessageItem) arg0.getItemAtPosition(arg2);
			if (item != null) {
				removeNewMsgFlicker(item);
				IntentUtils.startActivityForString_Three(getActivity(), ChatActivity.class,
						ConfigUtils.TalkingType, ConfigUtils.Group_Talking, ConfigUtils.Group_Talking, item.senderID, ConfigUtils.Group_Talking_Name, item.title);
			}
		}
	}
	//移除新消息闪动
	private void removeNewMsgFlicker(MessageItem item)
	{
		if(item==null)
		{return;}
		item.isNewMsg = false;
		LastChatRecordPersister.getInstance().update(item);
		currentItem = item;
		adapter.notifyDataSetChanged();
	}

	private void updateListViewByDataSourceNoChange(boolean isLongState) {
		adapter.setIsLongState(isLongState);
		adapter.setCheckItemMap(checkedItemMap);
		adapter.notifyDataSetChanged();
		mListView.setAdapter(adapter);
	}

	private void putCheckedItemMap(int key) {
		if (checkedItemMap.containsKey(key)) {
			boolean value = checkedItemMap.get(key);
			if (value) {
				checkedItemMap.remove(key);
			}
		} else {
			checkedItemMap.put(key, true);
		}
	}

	public MessageItem getMsgItem(String name) {
		for (int i = 0; i < mMessageItems.size(); i++) {
			MessageItem item = mMessageItems.get(i);
			if (item != null && item.senderID.equals(name))
				return mMessageItems.get(i);
		}
		return null;
	}

	public void onEventMainThread(ChatEvent event) {
		try {
			//如果是系统消息，不触发也不记录到DB
			if (event.isSystemMsg||!event.isGroupChat||event.isEcho) {
				return;
			}
			if(event.groupID.equals(GGApplication.getInstance().TALKINGUSER))
			{
				return;
			}
			boolean isNewMsg = false;
			if (event.groupID == GGApplication.getInstance().getCurrentUser().getUserID()) {
				return;
			}
			MessageItem item = getMsgItem(event.groupID);
			if (item == null) {
				item = new MessageItem();

				isNewMsg = true;
			}
			GGGroup group = ClientGlobalCache.getInstance().getGroup(event.groupID);
			if (group == null) {
				return;
			}
			item.title = group.getName();
			item.time = new Date();
			item.senderID = event.groupID;
			item.isGroup = true;
			item.isNewMsg = true;
//			item.iconRes = R.drawable.folder;
			if (isNewMsg) {
				mMessageItems.add(0, item);
			} else {
                mMessageItems.remove(item);
				mMessageItems.add(0, item);
			}

			mHandler.post(new Runnable() {
				@Override
				public void run() {
					adapter.notifyDataSetChanged();
					//onLoad();p
				}
			});
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

    public void onEventMainThread(ClickToChatEvent event)
    {
        MessageItem item = getMsgItem(event.friendID);
		removeNewMsgFlicker(item);
    }

	public void onEventMainThread(GroupDeletedNotifyEvent event)
	{
		for (int i = 0; i < mMessageItems.size(); i++) {
			MessageItem item = mMessageItems.get(i);
			if (item != null && item.senderID.equals(event.groupID))
			{
				mMessageItems.remove(i);
				adapter.notifyDataSetChanged();
			}
		}
	}

	public void onEventMainThread(GroupUserChangedEvent event)
	{
		List<String> groupList=new ArrayList<>();
		groupList.add(event.groupID);
		ClientGlobalCache.getInstance().resetSomeGroups(groupList);
		String guestNames=this.getGuestNameStr(event.guests);
		String operateUserName=ClientGlobalCache.getInstance().getUser(event.operateUserID)==null?"":ClientGlobalCache.getInstance().getUser(event.operateUserID).getName();
		String msg ="" ;
		GGGroup group= ClientGlobalCache.getInstance().getGroup(event.groupID);
		switch (event.groupChangedType)
		{
			case MyselfBePulledIntoGroup:
				ClientGlobalCache.getInstance().reLoadCurrentUserFromServer();
				if(group != null) {
					MessageItem item = this.groupConvertToMessageItem(group);
					mMessageItems.add(0, item);
					adapter.notifyDataSetChanged();
					msg=String.format("%s已被拉进讨论组",guestNames);
				}
				break;
			case OtherBePulledIntoGroup:
				msg=String.format("%s已被拉进讨论组",guestNames);
				break;
			case MyselfBeRemovedFromGroup:
				ClientGlobalCache.getInstance().reLoadCurrentUserFromServer();
				msg=String.format("您已被移出讨论组");
				break;
			case OtherBeRemovedFromGroup:
				msg=String.format("%s已被移出讨论组",guestNames);
				break;
			case SomeoneJoin:
				msg=String.format("%s已加入讨论组",guestNames);
				break;
			case SomeoneQuit:
				msg=String.format("%s已退出讨论组",guestNames);
				break;
		}
		Manager.getInstance().sendSystemMessage(event.groupID,msg,true);
	}

	public void onEventMainThread(GroupInfoChangedEvent event)
	{
		for (int i = 0; i < mMessageItems.size(); i++) {
			MessageItem item = mMessageItems.get(i);
			if (item != null && item.senderID.equals(event.groupID))
			{
				item.title=event.groupName;
				item.lastWord=event.groupAnnounce;
				adapter.notifyDataSetChanged();
				return;
			}
		}
	}


	private MessageItem groupConvertToMessageItem(GGGroup group)
	{
		if(group==null)
		{
			return null;
		}
		MessageItem item=new MessageItem();
		item.isGroup=true;
		item.senderID=group.getGroupID();
		item.title=group.getName();
		item.lastWord = group.getAnnounce();
//		item.iconRes=R.drawable.folder;
		return item;
	}

	//获取被拉进群的用户名
	private String getGuestNameStr(List<String> guestIDs)
	{
		String str="";
		for (String guestID:guestIDs)
		{
			if(ClientGlobalCache.getInstance().isUserExist(guestID))
			{
				str+=","+ClientGlobalCache.getInstance().getUser(guestID).getName();
			}
		}
		if(str.length()>0)
		{
			str=str.substring(1);
		}
		return str;
	}



	@Override
	public void onDestroyView() {
		super.onDestroyView();
		EventBus.getDefault().unregister(this);
	}
}
